package com.futu.attraction.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.futu.attraction.config.TemperatureAlert;
import com.futu.attraction.service.AmapService;
import com.futu.common.annotation.NoLoginRequired;
import com.futu.common.service.WeatherService;
import com.futu.common.utils.RedisUtil;
import com.futu.common.vo.Result;

import com.futu.common.vo.WeatherForecastVO;
import com.futu.common.vo.WeatherRealTimeVO;
import com.futu.kafka.TemperatureReading;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.Date;

@RestController
@RequestMapping("/amap")
public class AmapController {
    @Resource
    private  AmapService amapService;
    @Resource
    private WeatherService weatherService;
    @Resource
    private RedisUtil redisUtil;

    /**
     * 驾车路线规划接口
     * @param origin 起点坐标，格式为"经度,纬度"
     * @param destination 终点坐标，格式为"经度,纬度"
     * @return 路线规划结果
     */
    @GetMapping("/route")
    @NoLoginRequired
    public Result<JSONObject> getRoute(@RequestParam String origin, @RequestParam String destination) {
        try {
            JSONObject result = amapService.getDrivingRoute(origin, destination);
            // 检查API返回状态
            if (result != null && "1".equals(result.getString("status"))) {
                return Result.success(result);
            } else {
                String errorMsg = result != null ? result.getString("info") : "未知错误";
                return Result.error("路线规划失败: " + errorMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("路线规划请求异常: " + e.getMessage());
        }
    }

    /**
     * 步行路线规划接口
     * @param origin 起点坐标，格式为"经度,纬度"
     * @param destination 终点坐标，格式为"经度,纬度"
     * @return 路线规划结果
     */
    @GetMapping("/route/walking")
    @NoLoginRequired
    public Result<JSONObject> getWalkingRoute(@RequestParam String origin, @RequestParam String destination) {
        try {
            JSONObject result = amapService.getWalkingRoute(origin, destination);
            // 检查API返回状态
            if (result != null && "1".equals(result.getString("status"))) {
                return Result.success(result);
            } else {
                String errorMsg = result != null ? result.getString("info") : "未知错误";
                return Result.error("步行路线规划失败: " + errorMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("步行路线规划请求异常: " + e.getMessage());
        }
    }

    /**
     * 公交路线规划接口
     * @param origin 起点坐标，格式为"经度,纬度"
     * @param destination 终点坐标，格式为"经度,纬度"
     * @param city 城市名称，如"北京"
     * @return 路线规划结果
     */
    @GetMapping("/route/transit")
    @NoLoginRequired
    public Result<JSONObject> getTransitRoute(
            @RequestParam String origin,
            @RequestParam String destination,
            @RequestParam(required = false, defaultValue = "北京") String city) {
        try {
            JSONObject result = amapService.getTransitRoute(origin, destination, city);
            // 检查API返回状态
            if (result != null && "1".equals(result.getString("status"))) {
                return Result.success(result);
            } else {
                String errorMsg = result != null ? result.getString("info") : "未知错误";
                return Result.error("公交路线规划失败: " + errorMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("公交路线规划请求异常: " + e.getMessage());
        }
    }

    @GetMapping("/api/weather/current")//根据城市编码查询实时天气
    public Result<WeatherRealTimeVO> getCurrentWeather(
            @RequestParam String scenicSpotId,
            @RequestParam String cityCode) {
        try {
            WeatherRealTimeVO data = weatherService.getCurrentWeather(scenicSpotId, cityCode);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取实时天气失败：" + e.getMessage());
        }
    }


    @GetMapping("/currentByName")//根据名称查询实时天气
    public Result<WeatherRealTimeVO> getCurrentWeatherByName(@RequestParam String cityName) {
        try {
            WeatherRealTimeVO vo = weatherService.getCurrentWeatherByCityName(cityName);
            
            // 只有当温度数据有效时才发送到Kafka
            if (vo != null && vo.getTemperature() != null) {
                try {
                    double temperature = Double.parseDouble(vo.getTemperature());
                    
                    // 验证温度数据的合理性（例如，中国大部分地区温度范围在-50°C到50°C之间）
                    if (temperature >= -50 && temperature <= 50) {
                        TemperatureReading temperatureReading = new TemperatureReading();
                        temperatureReading.setCity(cityName);
                        temperatureReading.setTemperature(temperature);
                        temperatureReading.setTimestamp(new Date());
                        
                        // 添加数据来源标记，表明这是从高德API获取的真实数据
                        String jsonString = JSON.toJSONString(temperatureReading);
                        
                        // 记录发送的温度数据
                        System.out.println("发送温度数据到Kafka: " + jsonString);
                        
                        // 发送到Kafka
                        weatherService.sendTemperatureReading(jsonString);
                        System.out.println("温度数据发送成功");
                    } else {
                        System.out.println("温度数据超出合理范围，不发送到Kafka: " + temperature + "°C");
                    }
                } catch (NumberFormatException e) {
                    System.err.println("温度数据格式无效，无法解析为数字: " + vo.getTemperature());
                }
            } else {
                System.out.println("未获取到有效的温度数据，不发送到Kafka");
            }

            if (vo != null) {
                return Result.success(vo);
            } else {
                return Result.error("未获取到天气数据");
            }
        } catch (Exception e) {
            return Result.error("获取天气异常: " + e.getMessage());
        }
    }
    @GetMapping("/forecastByName")//根据名称查询天气预报
    public WeatherForecastVO getWeatherForecastByName(@RequestParam String cityName) {
        // 方式2（推荐）：直接调用
        return weatherService.getWeatherForecastByCityName(cityName);
    }
    @GetMapping("/api/weather/forecast")//根据城市编码查询天气预报
    public Result<WeatherForecastVO> getWeatherForecast(
            @RequestParam String scenicSpotId,
            @RequestParam String cityCode) {
        try {
            WeatherForecastVO data = weatherService.getWeatherForecast(scenicSpotId, cityCode);
            return Result.success(data);
        } catch (Exception e) {
            return Result.error("获取天气预报失败：" + e.getMessage());
        }
    }

    @GetMapping("/temperature/alert")
    @NoLoginRequired
    public Result<TemperatureAlert> getTemperatureAlert(@RequestParam String cityName) {
        try {
            System.out.println("收到温度告警查询请求，城市名称: " + cityName);
            
            // 验证城市名称
            if (cityName == null || cityName.trim().isEmpty()) {
                System.err.println("城市名称为空");
                return Result.error("城市名称不能为空");
            }
            
            // 规范化城市名称
            cityName = cityName.trim();
            
            // 每次都直接获取实时天气数据，不使用Redis缓存
            WeatherRealTimeVO realTimeWeather = weatherService.getCurrentWeatherByCityName(cityName);
            if (realTimeWeather == null) {
                System.err.println("无法获取实时天气数据，城市: " + cityName);
                return Result.error("获取实时天气数据失败");
            }
            
            System.out.println("成功获取实时天气数据，城市: " + cityName + ", 天气: " + realTimeWeather.getWeather());
            
            // 解析实时温度
            double realTimeTemperature;
            try {
                realTimeTemperature = Double.parseDouble(realTimeWeather.getTemperature());
                System.out.println("实时温度: " + realTimeTemperature + "°C, 城市: " + cityName);
            } catch (NumberFormatException e) {
                System.err.println("实时温度数据格式无效: " + realTimeWeather.getTemperature() + ", 城市: " + cityName);
                return Result.error("温度数据格式无效");
            }
            
            // 创建温度数据对象，使用传入的城市名作为sensorId
            TemperatureAlert temperatureData = new TemperatureAlert(
                cityName,  // 使用传入的城市名称作为sensorId
                realTimeTemperature,
                new Date(),
                ""  // 消息稍后设置
            );
            
            // 根据实时温度设置消息和告警状态
            if (realTimeTemperature > 35) {
                temperatureData.setMessage("温度过高，注意防暑降温");
                temperatureData.setAlert(true);
            } else if (realTimeTemperature >= 30) {
                temperatureData.setMessage("温度较高，请适当补充水分");
                temperatureData.setAlert(true);
            } else if (realTimeTemperature > 25) {
                temperatureData.setMessage("温度舒适，适合户外活动");
                temperatureData.setAlert(false);
            } else if (realTimeTemperature > 10) {
                temperatureData.setMessage("温度适宜，建议适当增减衣物");
                temperatureData.setAlert(false);
            } else if (realTimeTemperature > 0) {
                temperatureData.setMessage("温度较低，注意保暖");
                temperatureData.setAlert(false);
            } else {
                temperatureData.setMessage("温度很低，请注意防寒保暖");
                temperatureData.setAlert(false);
            }
            
            System.out.println("返回温度数据: " + JSON.toJSONString(temperatureData) + ", 城市: " + cityName);
            return Result.success(temperatureData);
            
        } catch (Exception e) {
            System.err.println("获取温度告警失败: " + e.getMessage() + ", 城市: " + cityName);
            e.printStackTrace();
            return Result.error("获取温度告警失败：" + e.getMessage());
        }
    }
    
    /**
     * 清除所有温度告警数据
     * @return 清除结果
     */
    @GetMapping("/temperature/clear-all-alerts")
    @NoLoginRequired
    public Result<String> clearAllTemperatureAlerts() {
        try {
            // 清除所有temperature_alert开头的键
            redisUtil.deleteKeysWithPattern("temperature_alert:*");
            
            // 清除所有temperature:alert开头的键（兼容不同格式）
            redisUtil.deleteKeysWithPattern("temperature:alert:*");
            
            System.out.println("已清除所有温度告警数据");
            return Result.success("已清除所有温度告警数据");
        } catch (Exception e) {
            System.err.println("清除温度告警数据失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("清除温度告警数据失败：" + e.getMessage());
        }
    }

    /**
     * 清除指定城市的温度告警数据
     * @param cityName 城市名称
     * @return 清除结果
     */
    @GetMapping("/temperature/clear-city-alert")
    @NoLoginRequired
    public Result<String> clearCityTemperatureAlert(@RequestParam String cityName) {
        try {
            if (cityName == null || cityName.trim().isEmpty()) {
                return Result.error("城市名称不能为空");
            }
            
            // 清除指定城市的温度告警
            String alertKey = "temperature_alert:" + cityName;
            redisUtil.delete(alertKey);
            
            System.out.println("已清除城市 " + cityName + " 的温度告警数据");
            return Result.success("已清除城市 " + cityName + " 的温度告警数据");
        } catch (Exception e) {
            System.err.println("清除城市温度告警数据失败: " + e.getMessage());
            e.printStackTrace();
            return Result.error("清除城市温度告警数据失败：" + e.getMessage());
        }
    }
}
